﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media;

namespace IP20.Procdure
{
    public class HueToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is int hue)
            {
                // 将 HSV 的 Hue（0-360）转换为 RGB 颜色（固定 S=1, V=1）
                return ColorFromHsv(hue, saturation: 1, value: 1);
            }
            else if (value is string strHue)
            {
                // 将 HSV 的 Hue（0-360）转换为 RGB 颜色（固定 S=1, V=1）
                return ColorFromHsv(int.Parse(strHue), saturation: 1, value: 1);
            }
            return Brushes.Transparent;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        // HSV 转 RGB 算法
        private static Color ColorFromHsv(double hue, double saturation, double value)
        {
            // 使用兼容性Clamp
            hue = Math.Max(0, Math.Min(360, hue));
            saturation = Math.Max(0, Math.Min(1, saturation));
            value = Math.Max(0, Math.Min(1, value));

            double c = value * saturation;
            double x = c * (1 - Math.Abs((hue / 60) % 2 - 1));
            double m = value - c;

            double r, g, b;
            if (hue >= 0 && hue < 60) { r = c; g = x; b = 0; }
            else if (hue < 120) { r = x; g = c; b = 0; }
            else if (hue < 180) { r = 0; g = c; b = x; }
            else if (hue < 240) { r = 0; g = x; b = c; }
            else if (hue < 300) { r = x; g = 0; b = c; }
            else { r = c; g = 0; b = x; }

            return Color.FromRgb(
                (byte)((r + m) * 255),
                (byte)((g + m) * 255),
                (byte)((b + m) * 255));
        }
    }
}